const router = require("koa-router")();
const result = require("../../config/result");
const {
  getToken,
  addUrl,
  whereUrl,
  updateUrl,
} = require("../../config/databaseapi");
const {
  regCheck,
  shopInfor,
  categoryCheck,
  unitCheck,
  dishCheck,
  tableCheck
} = require("../../config/checking");
const { Auth } = require("../../token/auth");
const { upload, cosfun,cosbuffer } = require("../../cos/cos");
const {Code} = require('../../config/codeImg')
const moment = require("moment");
moment.locale("zh-cn");
//添加桌号接口
router.post('/qrcode', new Auth().m ,async ctx => {
    let {table} =ctx.request.body
    new tableCheck(ctx,table).start()
    let time = moment().utcOffset(8).format('YYYY-MM-DD HH:mm:ss')
    try {
        //判断是否存在桌号
        const query = `db.collection('table').where({table:'${table}'}).get()`
        const res = await new getToken().posteve(whereUrl,query)
        if (res.data.length > 0) {
            new result(ctx,'该桌号已存在',202).answer()
        }else{
            let resCode = await new getToken().qrcode(table)
            const resImg = await cosbuffer(Code(),resCode.data)
            let codeImg = 'https://'+resImg
            let tableQuery = `db.collection('table').add({data:{time:'${time}',table:'${table}',code:'${codeImg}'}})`
            await new getToken().posteve(addUrl,tableQuery)
            new result(ctx,'添加成功',200).answer()
        }
    } catch (error) {
        new result(ctx,'服务器错误',500).answer()
    }
})
//请求桌号数据库接口
router.get('/getqrcode', new Auth().m ,async ctx => {
    let {page} = ctx.query
    let sk = Number(page) * 10
    const query = `db.collection('table').orderBy('time','desc').limit(10).skip(${sk}).get()`
    try {
        const res = await new getToken().posteve(whereUrl,query)
        const data = res.data.map(item => {
            return JSON.parse(item)
        })
        let total = {total : res.pager.Total }
        const arr = {...{result:data},...total}
        new result(ctx,'SUCCESS',200,arr).answer()
    } catch (error) {
        new result(ctx,'服务器发生错误',500).answer()
    }

})
module.exports = router.routes();